﻿using Microsoft.Data.Sqlite;
using SSC.Models;

namespace SSC.Services
{
    public class OperationLogService
    {
        // 添加操作日志
        public bool AddLog(string userName, string operationType, string description)
        {
            var log = new LogModel
            {
                DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                UserName = userName,
                OperationType = operationType,
                Description = description
            };

            string query = @"INSERT INTO tbOperationLogs (DateTime, UserName, OperationType, Description)
                             VALUES (@DateTime, @UserName, @OperationType, @Description)";

            return App.DatabaseService.Execute(query, log);
        }

        // 查询操作日志
        public List<LogModel> GetLogs(DateTime? startDate = null, DateTime? endDate = null)
        {
            string query = "SELECT * FROM tbOperationLogs WHERE 1=1";
            List<SqliteParameter> parameters = new();

            if (startDate.HasValue)
            {
                query += " AND DateTime >= @StartDate";
                parameters.Add(new SqliteParameter("@StartDate", startDate.Value.ToString("yyyy-MM-dd HH:mm:ss")));
            }

            if (endDate.HasValue)
            {
                query += " AND DateTime <= @EndDate";
                parameters.Add(new SqliteParameter("@EndDate", endDate.Value.ToString("yyyy-MM-dd HH:mm:ss")));
            }

            query += " ORDER BY DateTime DESC";

            return App.DatabaseService.GetAll<LogModel>(query, parameters.ToArray());
        }
    }
}
